package postgres

import (
	"manager/model"
	"manager/model/entity"
	"manager/utils"
	"time"
)

var RouteList = &routeList{}

type routeList struct{}

func (a *routeList) Create(m *entity.RouteList) (int64, error) {
	err := db.Create(m).Error
	return m.Id, err
}

func (a *routeList) Find(id int64) (*entity.RouteList, error) {
	e := &entity.RouteList{}
	err := db.Model(&entity.RouteList{}).First(&e, id).Error
	return e, err
}

func (a *routeList) Update(id int64, dict map[string]interface{}) error {
	return db.Model(&entity.RouteList{}).Where("id = ?", id).Updates(dict).Error
}

func (a *routeList) Delete(id int64) error {
	return db.Delete(&entity.RouteList{}, id).Error
}

// DeleteByParameter 根据参数删除行驶轨迹
func (a *routeList) DeleteByParameter(req *model.RouteListDeleteRequest) error {
	q := db.Model(&RouteList)
	if req.Id != 0 {
		q = q.Where("id = ?", req.Id)
	}
	if req.UserId != nil {
		q = q.Where("user_id = ?", *req.UserId)
	}
	if req.EbikeId != nil {
		q = q.Where("ebike_id = ?", *req.EbikeId)
	}
	return q.Delete(&entity.RouteList{}).Error
}

// ClearRouteList 清理行驶轨迹
func (a *routeList) ClearRouteList(userId, bikeId int64) error {
	// 清理不满足条件的数据
	return db.Where("user_id = ? and ebike_id = ? and ((mileage > 0 and mileage < 100) or (end_time - start_time < 200)) and is_finish > 0", userId, bikeId).Delete(&entity.RouteList{}).Error
}

// ClearExpireData 清理过期数据
func (a *routeList) ClearExpireData(userId, bikeId int64) error {
	defer utils.ExceptionCatch()

	// 清理过期无效的数据
	err := db.Where("user_id = ? and ebike_id = ? and mileage = 0 and is_finish = 0 and  created_at < ? ", userId, bikeId, time.Now().Unix()-24*3600).Delete(&entity.RouteList{}).Error
	if err != nil {
		return err
	}

	// 清理过期的数据
	err = db.Where("user_id = ? and ebike_id = ?  and created_at < ? ", userId, bikeId, time.Now().Unix()-60*24*3600).Delete(&entity.RouteList{}).Error
	if err != nil {
		return err
	}

	return nil
}

func (a *routeList) List(in *model.RouteListListRequest, isUpdate bool) (int, []*entity.RouteList, error) {
	var (
		q          = db.Model(&entity.RouteList{})
		err        error
		total      int64
		routeLists []*entity.RouteList
	)

	if in.Id > 0 {
		q = q.Where("id = ?", in.Id)
	}

	if in.StartTime > 0 {
		q = q.Where("created_at >= ?", in.StartTime)
	}

	if in.EndTime > 0 {
		q = q.Where("created_at < ?", in.EndTime)
	}

	if in.EbikeId > 0 {
		q = q.Where("ebike_id = ?", in.EbikeId)
	}

	if in.UserId > 0 {
		q = q.Where("user_id = ?", in.UserId)
	}

	if !isUpdate {
		q = q.Where("mileage > ? and end_time - start_time >= ?", 100, 200)
	}

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Order("created_at desc").Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&routeLists).Error; err != nil {
		return 0, nil, err
	}
	return int(total), routeLists, nil
}
